/* eslint-disable import/no-cycle */
import sm from 'sm-crypto';
import getTransferKey from '@/api-new/transfer';
import { MyResponse } from './net';

export default class EncryptionManager {
  private keyPairs: Map<string, any> = new Map();

  private updateInterval: number = 10 * 60 * 1000; // 10分钟

  // constructor() {
  // this.startKeyUpdateTimer();
  // }

  // 启动定时更新
  private startKeyUpdateTimer() {
    setInterval(() => {
      this.updateKeyPairs();
    }, this.updateInterval);
    setTimeout(() => {
      this.updateKeyPairs();
    }, 0);
  }

  // 更新密钥对
  async updateKeyPairs() {
    const result = await getTransferKey();

    console.log('result', result);
    this.keyPairs.set(result.keyId, result);
  }

  // 解密响应数据
  decryptResponse(response: MyResponse): any {
    if (response.summary && response.summary.encrypted === 1) {
      const { keyId } = response.summary;
      const keyPair = this.keyPairs.get(keyId);

      if (!keyPair) {
        throw new Error(`未找到密钥: ${keyId}`);
      }

      // console.log('secretData', response.secretData!.slice(2));
      // console.log('clientPrivateKey', keyPair.clientPrivateKey);

      // 使用SM2解密（需要引入SM2库）
      const decrypted = sm.sm2.doDecrypt(
        response.secretData!.slice(2),
        keyPair.clientPrivateKey
      );

      // console.log('decrypted', decrypted);

      return JSON.parse(decrypted);
    }

    return response.data;
  }
}
/* eslint-disable import/no-cycle */
